<template>
  <el-card class="card-box">
    <div class="header">
      <h2>设备维护计划管理</h2>
      <el-button type="primary" @click="showAddDrawer">
        <el-icon><Plus /></el-icon>添加维护计划
      </el-button>
    </div>

    <el-form inline class="filter-bar">
      <el-form-item label="设备ID:">
        <el-select
          v-model="searchMessage.serialNumber"
          filterable remote clearable reserve-keyword
          placeholder="请输入设备ID"
          :remote-method="fetchSerialSuggestions"
          :loading="loadingSerialNumbers"
          class="input-short"
        >
          <el-option
            v-for="item in serialNumberOptions"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search">
          <el-icon><Search /></el-icon>搜索
        </el-button>
        <el-button @click="searchWithNoCondition">
          <el-icon><Refresh /></el-icon>重置
        </el-button>
      </el-form-item>
    </el-form>

    <div class="responsive-table-container">
      <table class="custom-table">
        <thead>
          <tr>
            <th>编号</th>
            <th>设备ID</th>
            <th>创建人ID</th>
            <th>维护周期(天)</th>
            <th>维护内容</th>
            <th>下次维护</th>
            <th>创建时间</th>
            <th>更新时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in maintenancePlanList" :key="item.id">
            <td>{{ item.id }}</td>
            <td>{{ item.serialNumber }}</td>
            <td>{{ item.creatorId }}</td>
            <td>{{ item.cycle }}</td>
            <td class="truncate">{{ item.content }}</td>
            <td>{{ item.nextMaintenanceTime }}</td>
            <td>{{ item.createTime }}</td>
            <td>{{ item.updateTime }}</td>
            <td>
              <div class="action-btns">
                <el-button
                  :icon="Edit"
                  circle
                  plain
                  size="small"
                  type="primary"
                  @click="showEditDrawer(item)"
                />
                <el-button
                  :icon="Delete"
                  circle
                  plain
                  size="small"
                  type="danger"
                  @click="deleteBox(item.id)"
                />
              </div>
            </td>
          </tr>
          <tr v-if="maintenancePlanList.length === 0">
            <td colspan="9" class="text-center py-4">
              <el-empty description="暂无数据" />
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[3, 5, 7, 10]"
        layout="total, sizes, prev, pager, next, jumper"
        background
        :total="total"
        @size-change="onSizeChange"
        @current-change="onCurrentChange"
      />
    </div>

    <el-drawer 
      v-model="visibleDrawer" 
      :title="title" 
      direction="rtl" 
      size="50%"
      class="compact-drawer"
    >
      <el-form :model="formModel" label-width="120px" class="drawer-form">
        <el-form-item label="设备ID" required>
          <el-select
            v-model="formModel.serialNumber"
            filterable remote clearable reserve-keyword
            placeholder="请搜索并选择设备ID"
            :remote-method="fetchSerialSuggestions"
            :loading="loadingSerialNumbers"
            class="w-full"
          >
            <el-option v-for="item in serialNumberOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="维护周期(天)" required>
          <el-input-number
            v-model="formModel.cycle"
            placeholder="请输入天数"
            :min="1"
            :controls="false"
            class="w-full"
          />
        </el-form-item>
        <el-form-item label="维护内容" required>
          <el-input 
            v-model="formModel.content" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入内容" 
            class="w-full"
          />
        </el-form-item>
        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleSubmit" 
            :loading="isSubmitting"
            class="submit-btn"
          >
            <el-icon v-if="!isSubmitting"><Check /></el-icon>
            {{ isSubmitting ? '提交中...' : '提交' }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Edit, Delete, Plus, Search, Refresh, Check } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import { useTokenStore } from '@/stores/token'

const tokenStore = useTokenStore()

interface MaintenancePlan {
  id: number
  serialNumber: string
  creatorId: number
  cycle: number
  content: string
  nextMaintenanceTime: string
  createTime: string
  updateTime: string
}

interface MaintenancePlanListResponse {
  current: number
  total: number
  pages: number
  size: number
  records: MaintenancePlan[]
}

interface MaintenancePlanModel {
  serialNumber: string | null
  creatorId: number | null
  cycle: number | null
  content: string | null
}

const maintenanceApi = {
  getPlanList: (params: any) => request<MaintenancePlanListResponse>({ method: 'GET', url: '/maintenance/plan/page', params }),
  addPlan: (data: MaintenancePlanModel) => request<string>({ method: 'POST', url: '/maintenance/plan', data }),
  updatePlan: (id: number, data: MaintenancePlanModel) => request<string>({ method: 'PUT', url: `/maintenance/${id}`, data }),
  deletePlan: (id: number) => request<string>({ method: 'DELETE', url: `/maintenance/${id}` }),
  getSerialSuggestions: (keyword: string) => request<string[]>({ method: 'GET', url: '/device/serial/suggestions', params: { keyword } })
}

const maintenancePlanList = ref<MaintenancePlan[]>([])
const formModel = ref<MaintenancePlanModel>({ serialNumber: null, creatorId: 1, cycle: null, content: null })
const serialNumberOptions = ref<string[]>([])
const loadingSerialNumbers = ref(false)
const bufferName = [{ add: '添加维护计划' }, { edit: '编辑维护计划' }]
const title = ref('')
const visibleDrawer = ref(false)
const isSubmitting = ref(false)
const isEdit = ref(false)
const editingId = ref<number | null>(null)
const searchMessage = ref({ serialNumber: null as string | null })
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)

const fetchSerialSuggestions = async (query: string) => {
  if (query) {
    loadingSerialNumbers.value = true
    try {
      const res = await maintenanceApi.getSerialSuggestions(query)
      serialNumberOptions.value = res.data
      if (!res.data.includes(formModel.value.serialNumber!)) formModel.value.serialNumber = null
    } catch {
      ElMessage.error('获取设备序列号失败')
    } finally {
      loadingSerialNumbers.value = false
    }
  } else {
    serialNumberOptions.value = []
  }
}

onMounted(() => getDataListWithCondition())

const getDataListWithCondition = async () => {
  const params: any = { page: pageNum.value, size: pageSize.value, serialNumber: searchMessage.value.serialNumber,creatorId:tokenStore.id }
  
  Object.keys(params).forEach(key => (!params[key] && params[key] !== 0) && delete params[key])
  try {
    const res = await maintenanceApi.getPlanList(params)
    maintenancePlanList.value = res.data.records
    total.value = res.data.total
  } catch {
    ElMessage.error('获取数据失败')
  }
}

const handleSubmit = async () => {
  if (isSubmitting.value) return
  isSubmitting.value = true
  try {
    const { serialNumber, cycle, content } = formModel.value
    if (!serialNumber || !cycle || !content) {
      ElMessage.warning('请填写完整信息')
      return
    }
    if (!serialNumberOptions.value.includes(serialNumber)) {
      ElMessage.error('请选择有效的设备ID')
      return
    }
    if (isEdit.value && editingId.value !== null) {
      await maintenanceApi.updatePlan(editingId.value, formModel.value)
      ElMessage.success('修改成功')
    } else {
      await maintenanceApi.addPlan(formModel.value)
      ElMessage.success('提交成功')
    }
    visibleDrawer.value = false
    getDataListWithCondition()
  } catch {
    ElMessage.error('操作失败')
  } finally {
    isSubmitting.value = false
  }
}

const clearData = () => {
  formModel.value = { serialNumber: null, creatorId: tokenStore.id || null, cycle: null, content: null }
  serialNumberOptions.value = []
  isEdit.value = false
  editingId.value = null
}

const showAddDrawer = () => {
  clearData()
  title.value = bufferName[0].add!
  visibleDrawer.value = true
}

const showEditDrawer = (row: MaintenancePlan) => {
  clearData()
  isEdit.value = true
  editingId.value = row.id
  title.value = bufferName[1].edit!
  visibleDrawer.value = true
  formModel.value = { serialNumber: row.serialNumber, creatorId: row.creatorId, cycle: row.cycle, content: row.content }
  serialNumberOptions.value = [row.serialNumber]
}

const deleteBox = (id: number) => {
  ElMessageBox.confirm('您确定要删除这条记录吗?', '警告', {
    confirmButtonText: '删除', cancelButtonText: '取消', type: 'warning'
  }).then(async () => {
    try {
      await maintenanceApi.deletePlan(id)
      ElMessage.success('删除成功')
      getDataListWithCondition()
    } catch {
      ElMessage.error('删除失败')
    }
  }).catch(() => ElMessage.info('删除已取消'))
}

const search = () => { pageNum.value = 1; getDataListWithCondition() }
const searchWithNoCondition = () => { searchMessage.value.serialNumber = null; pageNum.value = 1; getDataListWithCondition() }
const onSizeChange = (size: number) => { pageSize.value = size; getDataListWithCondition() }
const onCurrentChange = (num: number) => { pageNum.value = num; getDataListWithCondition() }
</script>

<style lang="scss" scoped>
.card-box {
  width: 100%;
  max-width: 100%;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
  padding: 0;
  overflow: hidden;
}

.header {
  padding: 0.8rem 1.2rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e6eaf0;
  background-color: #f7f9fc;
  
  h2 {
    font-weight: 600;
    font-size: 1.4rem;
    color: #333;
    user-select: none;
    margin: 0;
  }
}

.filter-bar {
  padding: 0.8rem 1.2rem;
  background-color: #fafbfc;
  border-bottom: 1px solid #e6eaf0;
  display: flex;
  flex-wrap: nowrap;
  align-items: center;
  overflow-x: auto;
  white-space: nowrap;
  gap: 0.8rem;

  .el-form-item {
    margin-bottom: 0 !important;
    flex-shrink: 0;
    
    label {
      font-weight: 500;
      color: #606266;
      font-size: 0.9rem;
    }
    
    .input-short {
      width: 200px;
    }
  }

  .el-button {
    height: 32px;
    font-weight: 500;
    padding: 0 12px;
    flex-shrink: 0;
  }
}

.responsive-table-container {
  overflow-x: auto;
  background: #fff;
  padding: 0.8rem;
}

.custom-table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0 6px;
  font-size: 0.9rem;

  thead tr {
    background-color: #f5f7fa;
    color: #606266;
    font-weight: 600;
    user-select: none;
  }

  th, td {
    padding: 8px 12px;
    text-align: left;
    vertical-align: middle;
    white-space: nowrap;
  }

  th {
    font-size: 0.85rem;
  }

  tbody tr {
    background-color: #fff;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
    transition: background-color 0.2s ease;

    &:hover {
      background-color: #f4f9ff;
    }
  }

  .truncate {
    max-width: 200px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .action-btns {
    display: flex;
    gap: 0.4rem;

    .el-button {
      padding: 0;
      width: 28px;
      height: 28px;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 50%;
    }
  }
}

.pagination-container {
  background-color: #fafbfc;
  padding: 0.8rem;
  border-top: 1px solid #e6eaf0;
  display: flex;
  justify-content: center;
}

.text-center {
  text-align: center;
}

.py-4 {
  padding-top: 1rem;
  padding-bottom: 1rem;
}

/* 抽屉样式 */
.compact-drawer {
  :deep(.el-drawer__header) {
    padding: 16px 20px;
    border-bottom: 1px solid #ebeef5;
    margin-bottom: 0;
    
    span {
      font-weight: 500;
      font-size: 18px;
    }
  }
  
  :deep(.el-drawer__body) {
    padding: 20px;
  }
}

.drawer-form {
  .w-full {
    width: 100%;
  }
  
  .submit-btn {
    display: flex;
    align-items: center;
    gap: 6px;
    padding: 10px 24px;
  }
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .filter-bar {
    gap: 0.6rem;
    
    .input-short {
      width: 180px;
    }
  }
  
  .custom-table {
    font-size: 0.85rem;
    
    th, td {
      padding: 6px 8px;
    }
  }
}

@media (max-width: 992px) {
  .header {
    padding: 0.6rem 1rem;
    
    h2 {
      font-size: 1.2rem;
    }
  }
  
  .filter-bar {
    padding: 0.6rem 1rem;
  }
  
  .responsive-table-container {
    padding: 0.6rem;
  }
}
</style>